package 打牢基础30天.day01.my;

import 打牢基础30天.util.ArrUtil;

import java.lang.invoke.VarHandle;

/**
 * @Author yaya
 * @Create 2024/6/4 14:57
 * Description:
 */
public class Code01_SelectionSort {

    // 选择排序
    public static void selectionSort(int[] arr) {
        // 边界条件
        if (arr == null || arr.length < 2) return;

        for (int i = 0; i < arr.length; i++) {
            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            swap(arr, i, minIndex);
        }

    }

    public static void swap(int[] arr, int i, int j) {
        if (i == j || arr[i] == arr[j]) return;

        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void selectionSort2(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[minIndex]){
                    minIndex = j;
                }
            }
            swap(arr,minIndex, i);
        }
    }

    // test
    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 100;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] arr1 = ArrUtil.generateRandomArray(maxSize, maxValue);
            int[] arr2 = ArrUtil.copyArray(arr1);
            selectionSort2(arr1);
            ArrUtil.comparator(arr2);
            if (!ArrUtil.isEqual(arr1, arr2)) {
                succeed = false;
                ArrUtil.printArray(arr1);
                ArrUtil.printArray(arr2);
                break;
            }
        }
        System.out.println(succeed ? "Nice!" : "Fucking fucked!");

        int[] arr = ArrUtil.generateRandomArray(maxSize, maxValue);
        ArrUtil.printArray(arr);
        selectionSort(arr);
        ArrUtil.printArray(arr);
    }
}
